//
//  UINavigationBar+AlphaExtension.m
//  ViewContrerCategary
//
//  Created by Hongwei Wang on 2019/2/13 .
//  Copyright © 2019 Hongwei Wang. All rights reserved.
//

#import "objc/runtime.h"
#import "UIView+XUtilExtension.h"
#import "UINavigationBar+AlphaExtension.h"

@interface UINavigationBar ()

@property (assign, nonatomic) BOOL isClear;
@property (nonatomic, strong) MyNavView *myNavView; //自定义插入层，自定义操作都要在这一层上进行
@property (assign, nonatomic) NSInteger org_style;
@property (assign, nonatomic) BOOL isSetOpaque;
@property (assign, nonatomic) BOOL org_transucent;
@property (strong, nonatomic) UIImage *org_shadow;
@property (strong, nonatomic) UIImage *org_def_bg_image;
@end

@implementation UINavigationBar (AlphaExtension)

static const void *isClearKey = &isClearKey, *org_style_key = &org_style_key, *isSetOpaque_key = &isSetOpaque_key, *org_transucent_key = &org_transucent_key;
static const void *myNavViewKey = &myNavViewKey, *org_shadow_key = &org_shadow_key, *org_def_bg_image_key = &org_def_bg_image_key;

- (UIImage *)org_shadow {
    return objc_getAssociatedObject(self, org_shadow_key);
}

- (void)setOrg_shadow:(UIImage *)org_shadow {
    objc_setAssociatedObject(self, org_shadow_key, org_shadow, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIImage *)org_def_bg_image {
    return objc_getAssociatedObject(self, org_def_bg_image_key);
}

- (void)setOrg_def_bg_image:(UIImage *)org_def_bg_image {
    objc_setAssociatedObject(self, org_def_bg_image_key, org_def_bg_image, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSInteger)org_style {
    if (self.isSetOpaque) {
        return [objc_getAssociatedObject(self, org_style_key) integerValue];
    }
    return self.barStyle;
}

- (void)setOrg_style:(NSInteger)org_style {
    objc_setAssociatedObject(self, org_style_key, @(org_style), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)org_transucent {
    if (self.isClear) {
        return [objc_getAssociatedObject(self, org_transucent_key) boolValue];
    }
    return self.translucent;
}

- (void)setOrg_transucent:(BOOL)org_transucent {
    objc_setAssociatedObject(self, org_transucent_key, @(org_transucent), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)isSetOpaque {
    return [objc_getAssociatedObject(self, isSetOpaque_key) boolValue];
}

- (void)setIsSetOpaque:(BOOL)isSetOpaque {
    objc_setAssociatedObject(self, isSetOpaque_key, @(isSetOpaque), OBJC_ASSOCIATION_ASSIGN);
}

- (void)setMyNavView:(MyNavView *)myNavView {
    objc_setAssociatedObject(self, &myNavViewKey, myNavView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (MyNavView *)myNavView {
    return objc_getAssociatedObject(self, &myNavViewKey);
}

- (void)setHiddenBottom:(BOOL)hiddenBottom {
    BOOL old = self.hiddenBottom;
    if (old == hiddenBottom) {
        return;
    }
    if (self.myNavView) {
        self.myNavView.hiddenBottomLine = hiddenBottom;
    } else {
        UIImage *image = hiddenBottom ? [UIImage new] : nil;
        [self setShadowImage:image];
    }
}

- (BOOL)hiddenBottom {
    if (self.myNavView) {
        return self.myNavView.hiddenBottomLine;
    }
    return self.shadowImage ? YES : NO;
}

- (BOOL)isClear {
    return [objc_getAssociatedObject(self, isClearKey) boolValue];
}

- (void)setIsClear:(BOOL)isClear {
    objc_setAssociatedObject(self, isClearKey, @(isClear), OBJC_ASSOCIATION_ASSIGN);
}

- (void)setBarBackgroundColor:(UIColor *)color image:(UIImage *)image {
    [self clearSystemLayer];
    [self createMyNavView];
//    if (color || ![color isEqual:UIColor.clearColor]) {
    self.myNavView.backColor = color;
//    }
    self.myNavView.backImage = image;
//    ((UIView *)[self valueForKey:@"backgroundView"]).backgroundColor = color;
    
}

- (void)setBarAlpha:(CGFloat)alpha {
    [self clearSystemLayer];
    [self createMyNavView];
    self.myNavView.alpha = alpha;
}

- (void)setBarMyLayerHeight:(CGFloat)height {
    height = height < 0 ? 0 : height;
    [self clearSystemLayer];
    [self createMyNavView];
    [self.myNavView setFrame:CGRectMake(0, 0, self.bounds.size.width, height)];
}

- (void)createMyNavView {
    if (self.myNavView) {
        return;
    }
    //状态栏高度
    CGFloat statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    //导航栏高度
    CGFloat barHeight = self.bounds.size.height;
    CGRect barBounds = self.bounds;
    barBounds.size.height = statusHeight + barHeight;
    self.myNavView = [[MyNavView alloc]initWithFrame:barBounds];
    self.myNavView.translucent = self.org_transucent;
    //通过kvc找到系统导航栏背景层，把自定义层添加到背景层
    /* 系统背景层无法改变其属性 所以通过添加自定义层，改变自定义层去实现效果*/
    [[self valueForKey:@"backgroundView"] addSubview:self.myNavView];
}

- (void)setBarToBeSystem {
    if (self.myNavView) {
        [self.myNavView removeFromSuperview];
        self.myNavView = nil;
    }
    if (self.isClear) {
        self.translucent = self.org_transucent;
        [self setBackgroundImage:self.org_def_bg_image
                   forBarMetrics:UIBarMetricsDefault];
        [self setShadowImage:self.org_shadow];
        self.isClear = NO;
    }
    if (self.isSetOpaque) {
        self.barStyle = self.org_style;
        self.isSetOpaque = NO;
    }
}

- (void)clearSystemLayer {
    if (self.isClear) {
        return;
    }
    UIImage *img = [self backgroundImageForBarMetrics:UIBarMetricsDefault];
    if (img) {
        self.org_def_bg_image = img;
    }
    img = self.shadowImage;
    if (img) {
        self.shadowImage = img;
    }
    self.org_transucent = self.translucent;
    self.translucent = self.org_transucent;
    //通过插入空image把背景变透明
    [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //去掉系统底线，使用自定义底线
    [self setShadowImage:[UIImage new]];
    self.isClear = YES;

}

- (void)setImagePosition:(CGPoint)position {
    if (!self.myNavView) {
        return;
    }
    [self.myNavView setImagePosition:position];
}

- (void)setImageBottomLeft:(CGPoint)bottomleft {
    if (!self.myNavView) {
        return;
    }
    [self.myNavView setImageBottomLeft:bottomleft];
}

@end

#pragma mark -- 自定义导航栏层
@interface MyNavView()
@property (nonatomic, strong) UIImageView * backImageView;
@property (strong, nonatomic) UIVisualEffectView *eff_view;
@property (nonatomic, strong) UIView * bottomLine;
@end

@implementation MyNavView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        self.backColor = [UIColor whiteColor];
        [self creatMainUIByFrame:frame];
    }
    return self;
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [self layoutCustomView];
}

- (void)setAlpha:(CGFloat)alpha {
    [super setAlpha:alpha];
}

- (void)layoutCustomView {
    CGFloat height = self.frame.size.height;
    CGFloat width = self.frame.size.width;
    [self.bottomLine setFrame:CGRectMake(0, height-0.5, width, 0.5)];
}

- (void)creatMainUIByFrame:(CGRect)frame {
    CGFloat height = frame.size.height;
    CGFloat width = frame.size.width;
    [self.bottomLine setFrame:CGRectMake(0, height-0.5, width, 0.5)];
    [self addSubview:self.bottomLine];
}
- (void)setImagePosition:(CGPoint)position {
    if (!_backImageView) {
        return;
    }
    _backImageView.origin = position;
}

- (CGFloat)self_bootom_in_window {
    CGFloat height = self.height;
    if (@available(iOS 11, *)) {
        height += [UIApplication sharedApplication].keyWindow.safeAreaInsets.top;
    } else {
        height += 20.;
    }
    return height;
}

- (void)setImageBottomLeft:(CGPoint)bottomleft {
    if (!_backImageView) {
        return;
    }
    
    _backImageView.left = bottomleft.x;
    _backImageView.bottom = bottomleft.y;
    if (_backImageView.top + _backImageView.height < [self self_bootom_in_window]) {
        _backImageView.bottom = [self self_bootom_in_window];
    }
}
//设置图片背景颜色
- (void)setBackColor:(UIColor *)backColor {
    if (!backColor) {
        _backColor = [UIColor clearColor];
    }
    _backColor = backColor;
    if (backColor == UIColor.whiteColor) {
        self.bottomLine.backgroundColor = [UIColor grayColor];
    } else self.bottomLine.backgroundColor = backColor;
    self.backgroundColor = backColor;
}

//设置图片背景透明度

//设置图片
- (void)setBackImage:(UIImage *)backImage {
    _backImage = backImage;
    if (!backImage) {
        if (_backImageView) {
            [self.backImageView removeFromSuperview];
            [self.eff_view removeFromSuperview];
        }
    } else {
        if (!_backImageView) {
            [self insertSubview:self.backImageView belowSubview:self.bottomLine];
            if (self.translucent) {
                [self insertSubview:self.eff_view belowSubview:self.bottomLine];
            }
        }
        self.backImageView.image = backImage;
        CGFloat rate = self.width/backImage.size.width;
        self.backImageView.size = (CGSize){self.width, rate * backImage.size.height};
    }
}

- (void)setTranslucent:(BOOL)translucent {
    _translucent = translucent;
    if (translucent) {
        [self insertSubview:self.eff_view belowSubview:self.bottomLine];
    } else {
        [self.eff_view removeFromSuperview];
    }
}

- (void)setHiddenBottomLine:(BOOL)hiddenBottomLine {
    _hiddenBottomLine = hiddenBottomLine;
    self.bottomLine.hidden = hiddenBottomLine;
}

#pragma mark -- 懒加载视图
- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _backImageView.clipsToBounds = YES;
        _backImageView.contentMode = UIViewContentModeScaleToFill;
    }
    return _backImageView;
}

- (UIVisualEffectView *)eff_view {
    if (!_eff_view) {
        _eff_view = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
        _eff_view.frame = self.bounds;
        _eff_view.tintColor = [UIColor blueColor];
        _eff_view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _eff_view.tag = 0xff001f;
    }
    return _eff_view;
}

- (UIView *)bottomLine {
    if (!_bottomLine) {
        _bottomLine = [UIView new];
//        [_bottomLine setBackgroundColor:[UIColor grayColor]];
//        _bottomLine.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    }
    return _bottomLine;
}
@end
